package com.example.app.controller.game;

import com.alibaba.fastjson.JSON;
import com.example.app.domain.BaseDescriptionValueVo;
import com.example.app.domain.WPParam;
import com.example.app.domain.game.GameInfoVo;
import com.example.app.domain.game.GameItemVO;
import com.example.app.domain.game.GameListVO;
import com.example.module.module.category.entity.Category;
import com.example.module.module.category.service.CategoryService;
import com.example.module.module.game.entity.Game;
import com.example.module.module.game.service.GameService;
import com.example.module.utils.BaseUtils;
import com.example.module.utils.ImageUtils;
import com.example.module.utils.Response;
import com.example.module.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/game")
public class GameController {

    @Autowired
    private GameService gameService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public Response getGameList(@RequestParam(required = false) String wp,
                                @RequestParam(required = false) String keyword) {

        WPParam baseWp = new WPParam();
        if (!BaseUtils.isEmpty(wp)) {
            byte[] bytes = Base64.getUrlDecoder().decode(wp.getBytes(StandardCharsets.UTF_8));
            String realWp = new String(bytes, StandardCharsets.UTF_8);
            try {
                baseWp = JSON.parseObject(realWp, WPParam.class);
            } catch (Exception e) {
                return new Response(4004);
            }
        } else {
            baseWp.setPage(1);
            baseWp.setKeyword(keyword);
        }
        String pageSize = SpringUtils.getProperty("application.pageSize");

        List<Game> games = gameService.getAllGames(baseWp.getPage(), Integer.parseInt(pageSize), keyword);
        Boolean isEnd = games.size() < Integer.parseInt(pageSize);

        // 收集所有categoryId
        List<Long> categoryIds = games.stream()
                .map(Game::getCategoryId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询分类信息
        List<Category> categories = categoryService.listByIds(categoryIds);
        Map<Long, Category> categoryMap = categories.stream()
                .collect(Collectors.toMap(Category::getId, Function.identity()));

        List<GameItemVO> gameItems = games.stream()
                .map(game -> {
                    GameItemVO itemVO = new GameItemVO();
                    itemVO.setId(game.getId());
                    // 处理图片信息
                    GameItemVO.ImageInfo imageInfo = new GameItemVO.ImageInfo();
                    String imageUrl = game.getCoverImages();

                    // 处理图片URL
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        // 设置原图URL（去掉参数保留基础地址）
                        imageInfo.setUrl(imageUrl.split("\\?")[0]);
                        // 从文件名提取宽高比
                        Float aspectRatio = ImageUtils.parseAspectRatio(imageUrl);
                        imageInfo.setAr(String.valueOf(aspectRatio));
                    } else {
                        // 设置默认图片URL和宽高比
                        imageInfo.setUrl("");
                        imageInfo.setAr("1.0");
                    }

                    itemVO.setImage(imageInfo);
                    itemVO.setGameName(game.getGameName());
                    itemVO.setPlayerNumber(game.getPlayerNumber());
                    Long categoryId = game.getCategoryId();
                    Category category = categoryMap.get(categoryId);
                    if (category != null) {
                        itemVO.setCategoryName(category.getName());
                    } else {
                        // 处理分类不存在的情况
                        itemVO.setCategoryName("未知分类");
                    }
                    return itemVO;
                })
                .collect(Collectors.toList());

        WPParam nextWPParam = new WPParam();
        nextWPParam.setPage(baseWp.getPage()+1);     // 下一页
        nextWPParam.setKeyword(keyword);   // 透传当前 keyword
        String nextWP;
        try {
            // 1. JSON序列化
            String jsonStr = JSON.toJSONString(nextWPParam);

            // 2. Base64 URL安全编码
            byte[] encodedBytes = Base64.getUrlEncoder()
                    .withoutPadding()  // 去掉末尾填充符
                    .encode(jsonStr.getBytes(StandardCharsets.UTF_8));

            nextWP = new String(encodedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            // 编码失败时返回空参数或默认值
            nextWP = "";
        }

        GameListVO gameListVO = new GameListVO();
        gameListVO.setList(gameItems);
        gameListVO.setIsEnd(isEnd);
        gameListVO.setWp(nextWP);

        return new Response(1001, gameListVO);
    }


    @GetMapping("/info")
    public Response getGameInfo(@RequestParam Long gameId) {
        Game game = gameService.getById(gameId);

        if (BaseUtils.isEmpty(game)) {
            return new Response(4004);
        }

        Category category = categoryService.getById(gameId);
        String categoryName = category != null ? category.getName() : null;
        String categoryImage = category != null ? category.getImage() : null;

        GameInfoVo gameInfoVO = new GameInfoVo();
        gameInfoVO.setTitle(game.getTitle());
        gameInfoVO.setCreateTime(game.getCreateTime());
        gameInfoVO.setCoverImages(game.getCoverImages());
        gameInfoVO.setGameName(game.getGameName());
        gameInfoVO.setReleaseDate(game.getReleaseDate());
        gameInfoVO.setPrice(game.getPrice());
        try {
            List<BaseDescriptionValueVo> descriptions = JSON.parseArray(game.getGameDescription(), BaseDescriptionValueVo.class);
            gameInfoVO.setGameDescription(descriptions);
        }catch (Exception cause){
            return new Response(4004);
        }
        gameInfoVO.setRating(game.getRating());
        gameInfoVO.setCategoryName(categoryName);
        gameInfoVO.setCategoryImage(categoryImage);

        return new  Response(1001,gameInfoVO);
    }






}